/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/
package com.sankuai.xm.kafka.client.utils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {
	private static final AtomicInteger poolNumber = new AtomicInteger(1);
	private static final AtomicInteger threadNumber = new AtomicInteger(1);
	private static final String DEFAULT_POOL_PRIFEX = "THREAD-POOL";
	private final ThreadGroup group;
	private final String namePrefix;
	private final boolean isDaemon;

	public NamedThreadFactory() {
		this("THREAD-POOL", false);
	}

	public NamedThreadFactory(String name) {
		this(name, false);
	}

	public NamedThreadFactory(String preffix, boolean daemon) {
		StringBuffer sb = new StringBuffer();
		SecurityManager s = System.getSecurityManager();
		this.group = ((s != null) ? s.getThreadGroup() : Thread.currentThread()
				.getThreadGroup());
		this.namePrefix = sb.append(preffix).append("-")
				.append(poolNumber.getAndIncrement()).append("-THREAD-")
				.toString();
		this.isDaemon = daemon;
	}

	public Thread newThread(Runnable r) {
		Thread t = new Thread(this.group, r, this.namePrefix
				+ threadNumber.getAndIncrement(), 0L);
		t.setDaemon(this.isDaemon);
		if (t.getPriority() != 5) {
			t.setPriority(5);
		}
		return t;
	}
}